/*
 * yCacheField JQuery Plugin
 *
 * Copyright (c) 2011 Yaroslav Dobzhanskyi
 * licensed under the MIT license
 * http://www.opensource.org/licenses/mit-license.php
 *
 * needs 'jQuery Cookie plugin' by Klaus Hartl for proper work
 */

(function( $ ){
	$.fn.yCacheField = function(new_opts){
	
		var options = {
			expire: 7,
			prefix: "cached_",
			delay: 1000
		};		
		
		if(new_opts)
		{
			$.extend(options, new_opts);
		}
		
		this.each(function(){
			
			var inputObject = $(this);
			var inputID = inputObject.attr("name");
			var cookieID = options.prefix + inputID;			
			var timeOut_var;
			
			if($.cookie(cookieID) != null)
			{
				inputObject.val($.cookie(cookieID));
			}
			
			var saveToCache = function()
			{
				if (inputObject.val() != "") {
					$.cookie(cookieID, inputObject.val(), {
						expires: options.expire,
						path: '/'
					});
				} else {
					$.cookie(cookieID, null, {path:'/'});
				}
			}
			
			inputObject.keyup(function(e){
				clearTimeout(timeOut_var);
				timeOut_var = setTimeout(saveToCache, options.delay);
			});
			
			inputObject.blur(function(e){
				clearTimeout(timeOut_var);
				saveToCache();
			});			
			
		});
		
		
	};
})( jQuery );